﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DocumentModel;
using AmazonDynamoDBStub.Helpers;

namespace AmazonDynamoDBStub.Extensions
{
    public static class PrimitiveExtensions
    {
        /// <summary>
        /// Add only for Numeric
        /// </summary>
        public static Primitive Add(this Primitive left, Primitive right)
        {
            if (left == null)
            {
                throw new ArgumentNullException("left");
            }

            if (right == null)
            {
                throw new ArgumentNullException("right");
            }

            if (left.Type != DynamoDBEntryType.Numeric || right.Type != DynamoDBEntryType.Numeric)
            {
                throw new NotSupportedException();
            }

            Type[] types = new Type[] { typeof(Int64), typeof(Double) };

            foreach (var t in types)
            {
                dynamic leftNum, rightNum;

                try
                {
                    leftNum = t.DynamicCast(left);
                    rightNum = t.DynamicCast(right);
                }
                catch (TargetInvocationException ex)
                {
                    if (ex.InnerException.GetType() != typeof(InvalidCastException))
                    {
                        throw;
                    }

                    continue;
                }

                dynamic result = leftNum + rightNum;
                return new Primitive(result.ToString(), true);
            }

            throw new InvalidCastException();
        }
    }
}
